import React, { useEffect, useMemo, useState } from 'react';
import {
  Input,
  Notification,
  Tree,
  Grid, Skeleton
} from '@arco-design/web-react';
import { TreeDataType } from '@arco-design/web-react/es/Tree/interface';
import useLocale from '@/utils/useLocale';
import locale from '@/locale';
import instance from '@/utils/request';
import { convertToTreeOptions } from '@/constants/functions';

const { Row, Col } = Grid;

export default (props: {
  onSelected: (record: TreeDataType) => void,
}) => {
  const t = useLocale(locale);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<TreeDataType[]>([]);
  const [inputValue, setInputValue] = useState('');
  const treeData = useMemo(() => {
    if (!inputValue) {
      return data;
    } else {
      return searchData(inputValue);
    }
  }, [inputValue, data]);

  function onSearchTitle({ title }) {
    if (inputValue) {
      const index = title.toLowerCase().indexOf(inputValue.toLowerCase());
      if (index === -1) {
        return title;
      }
      const prefix = title.substr(0, index);
      const suffix = title.substr(index + inputValue.length);
      return (
        <span> {prefix}
          <span style={{ background: 'rgba(128, 128, 128, 0.5)' }}>
            {title.substr(index, inputValue.length)}
          </span>
          {suffix}
        </span>
      );
    }

    return title;
  }

  function searchData(inputValue) {
    const loop = (data) => {
      const result = [];
      data.forEach((item) => {
        if (item.title.toLowerCase().indexOf(inputValue.toLowerCase()) > -1) {
          result.push({ ...item });
        } else if (item.children) {
          const filterData = loop(item.children);
          if (filterData.length) {
            result.push({ ...item, children: filterData });
          }
        }
      });
      return result;
    };
    return loop(data);
  }

  function fetchFactoryTree() {
    setLoading(true);
    instance
      .post('/api/structure/list', {})
      .then((res) => {
        if (res.data.code === 200) {
          setData(convertToTreeOptions(res.data.data));
        } else {
          setData([]);
          Notification.error({
            title: res.data.message,
            content: res.data.data
          });
        }
      }).finally(() => {
      setLoading(false);
    });
  }

  useEffect(() => {
    fetchFactoryTree();
  }, []);

  return (
    <Row style={{ height: '100%', background: 'white', padding: '1rem' }}>
      {
        loading ? (
          <Row>
            <Skeleton animation />
          </Row>
        ) : (
          <Row>
            <Col span={24} style={{ marginBottom: '1rem' }}>
              <Input.Search allowClear onChange={setInputValue}
                            placeholder={t['global.panel.factory-structure-panel.search.placeholder']} />
            </Col>
            <Col>
              <Tree multiple checkable showLine checkStrictly autoExpandParent
                    treeData={treeData} onCheck={props.onSelected} renderTitle={onSearchTitle}></Tree>
            </Col>
          </Row>
        )
      }
    </Row>
  );
}
